
import { Table, Popconfirm, Input, Form, Space, message, Modal, Button, Popover, Spin, Alert, Col, Row } from 'antd';
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { useDeletdbcMessageTransferMutation, useGetdbcMessageTransferQuery, usePostadddbcMessageTransferMutation, usePuteditdbcMessageTransferMutation, usePostdbcMessageTransferExcuteMutation } from '../../store/request/dataworksrequests/dbcmessagetransferrequest';




const DBCMessageTransferProp  = () => {
  const loginstate = useSelector(state => state.loginpara);//loginpara={isLogined,role:{key,loginname,authoritykey,avatarpath}}
  const [paraisselected, setparaisselected] = useState(false);//用于判断是否有选中行以此来空值执行按钮的生效
  const [selectpara, setselectpara] = useState("");//设置选中行的异常值并存储进state
  const [loading, setloading] = useState(false);
  const [excutesuccess, setexcutesuccess] = useState(-1);//设置是否执行成功，用于显示提示成功或失败信息
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);//设置表格里的是否选中异常值
  const [resultString, setResult] = useState("报文转csv执行成功");//存储请求处理执行的结果


  const popovercontent = (
    <div>
      <p>执行报文转csv，确保参数已选择</p>

    </div>
  );
  //选中时选取异常值
  const handleSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys);
    setparaisselected(true); // 执行按钮可以使用
    setselectpara(selectedRows[0]); // 把选中行的异常值存储到state中
    //console.log(selectedRows[0]);
  };
  const rowSelection = {
    type: "radio",
    selectedRowKeys,
    onChange: handleSelectChange,
  };
  //表格的单选
  // const rowSelection = {
  //   onChange: (selectedRowKeys, selectedRows) => {

  //     // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  //     setparaisselected(true);//执行按钮可以使用
  //     setselectpara(selectedRows[0])//把选中行的异常值存储到state中
  //     console.log(selectedRows[0]);
  //   },

  // };
  const [messageApi, contextHolder] = message.useMessage();
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  const getRandomuserParams = (params) => ({
    pagesize: params.pagination?.pageSize,
    page: params.pagination?.current,
    loginname: loginstate.role.loginname
    //...params,
  });
  const [editingKey, setEditingKey] = useState(''); // 初始化正在编辑的 key 的 state
  //用于是否打开添加modal的表单页面
  const [open, setOpen] = useState(false);
  //tableParams发生变化就会执行发送请求和参数
  const result = useGetdbcMessageTransferQuery(getRandomuserParams(tableParams));
  const [excutetrigger] = usePostdbcMessageTransferExcuteMutation();
  const [edittrigger] = usePuteditdbcMessageTransferMutation();
  const [deltrigger] = useDeletdbcMessageTransferMutation();
  const [addtrigger] = usePostadddbcMessageTransferMutation();
  const [form] = Form.useForm(); // 从 Form.useForm() 中解构 form
  const isEditing = (record) => record.key === editingKey; // 定义 isEditing 函数以检查记录是否正在被编辑

  const datapredictexcute = async () => {
    setloading(true);
    const r = await excutetrigger(selectpara);
    //console.log(r);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(3);
      const formattedResult = r.error.data.replace(/\n/g, '<br>');
      setResult(formattedResult);
      setexcutesuccess(1);

    } else {
      messageerror(3);
      setexcutesuccess(0);
    }
    setloading(false);

  };
  // const datacleanexcutecancle = async () => { };


  // 定义 edit 函数以将 editingKey state 设置为记录的 key
  //表单更新异常值只能用setFieldsValue方法，不能用setstate方法，这样就能获取原始值
  const edit = (record) => {

    form.setFieldsValue({
      vehicle: record.vehicle,
      project: record.project,
      ecnumber: record.ecnumber,
      originaldatapath: record.originaldatapath,
      savedatapath: record.savedatapath,
      selecteddirectory: record.selecteddirectory,
      dbcfilepath: record.onnxfilepath,
   
      //...record,  //一展开record，就会报错date.locale is not a function，但是之前arriveddate已经赋值为空字符串，所以除了arriveddate为空外，其余属性按照record展开
    });

    setEditingKey(record.key);
  };

  const messageerror = (editordel) => {
    //message.success('This is a success message');
    if (editordel === 0) {
      messageApi.open({
        type: 'error',
        content: '编辑失败',
      });
    }
    else if (editordel === 1) {
      messageApi.open({
        type: 'error',
        content: '删除失败',
      });
    }
    else if (editordel === 2) {
      messageApi.open({
        type: 'error',
        content: '添加失败',
      });
    }
    else {
      messageApi.open({
        type: 'error',
        content: '报文转csv失败，请查看日志',
      });
    }
    //console.log("消息框");
  };
  const messagesucess = (editordel) => {
    if (editordel === 0) {
      messageApi.open({
        type: 'success',
        content: '编辑成功',
      });
    }
    else if (editordel === 1) {
      messageApi.open({
        type: 'success',
        content: '删除成功',
      });
    }
    else if (editordel === 2) {
      messageApi.open({
        type: 'success',
        content: '添加成功',
      });
    }
    else {
      messageApi.open({
        type: 'success',
        content: '请求成功',
      });
    }
  };
  //添加异常值的表单页面
  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
      <Modal
        open={open}
        title="添加报文转csv参数记录"
        maskClosable={false}
        okText="添加"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={12}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="vehicle"
                label="车辆号"
                rules={[
                  {
                    required: true,
                    message: '请输入车辆号!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="project"
                label="项目名称"
                rules={[
                  {
                    required: true,
                    message: '请输入项目名称!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={12}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="ecnumber"
                label="边缘计算器编号"
                rules={[
                  {
                    required: true,
                    message: '请输入边缘计算器编号!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="selecteddirectory"
                label="文件夹日期"
                placeholder="可不填默认为all"
                rules={[
                  {
                    required: true,
                    message: '请输入文件夹日期!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="originaldatapath"
            label="源数据路径"
            rules={[
              {
                required: true,
                message: '请输入源数据路径!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="savedatapath"
            label="保存路径"
            rules={[
              {
                required: true,
                message: '请输入保存路径!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="dbcpath"
            label="dbc文件夹路径"
            placeholder="只需要填文件夹路径！！！"
            rules={[
              {
                required: true,
                message: '请输入dbc文件夹路径!',
              },
            ]}
          >
            <Input />
          </Form.Item>
        
        </Form>


      </Modal>
    );
  };

  //这个方法页面加载时就会不停的执行
  const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => { // 定义 EditableCell 组件并传入 props

    return (
      <td {...restProps}>
        {editing ? ( // 如果正在编辑，渲染带有相应 props 的 inputNode
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required: dataIndex !== "selecteddirectory" ? true : false,
                message: `请输入${title}!`,
              },
            ]}
          >
            {<Input />}
          </Form.Item>
        ) : (
          children // 否则渲染 children（文本）
        )}
      </td>
    );
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      editable: false,
      sorter: (a, b) => a.key - b.key,
      //render: (name) => `${name.first} ${name.last}`,

    },
    {
      title: '车辆号',
      dataIndex: 'vehicle',
      editable: true,

    },
    {
      title: '项目号',
      dataIndex: 'project',
      editable: true,

    },
    {
      title: '边缘计算器编号',
      dataIndex: 'ecnumber',
      editable: true,
    },
    {
      title: '源数据路径',
      dataIndex: 'originaldatapath',
      editable: true,

    },
    {
      title: '预测保存路径',
      dataIndex: 'savedatapath',
      editable: true,
      // width: '10%',
    },
    {
      title: '文件夹日期',
      dataIndex: 'selecteddirectory',
      editable: true,
      // width: '10%',
    },
    {
      title: 'dbc文件夹路径',
      dataIndex: 'dbcpath',
      editable: true,
      // width: '10%',
    },
   
    {
      //表格最后的操作按钮
      title: '操作',
      dataIndex: 'action',
      width: '3%',
      render: (_, record) => { // 使用 Popconfirm 组件渲染操作列
        const editable = isEditing(record);//判断这一行的key是否为editingKey，如果是则说明点击了edit，如果不是则说明没有点击

        return editable ? (

          <span>
            <a onClick={() => save(record.key)} style={{ marginRight: 8 }}>
              保存
            </a>
            <Popconfirm title="确定取消吗?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>

        ) : (
          //点击了edit就把这一行的key设为editingKey，重新渲染，然后editable变为true，显示保存和取消a标签，editingKey不等于空说明有行点了edit，则其他行都是disabled
          <Space size="middle">
            <a disabled={editingKey !== ''} onClick={() => edit(record)}>
              编辑
            </a>
            <Popconfirm title="确定删除吗?" onConfirm={() => deldata(record.key)} onCancel={cancel} okText="Yes" cancelText="No">
              <a >
                删除
              </a>
            </Popconfirm>
          </Space>
        );

      },
    },
  ];
  //添加异常值表单的添加方法
  const onAddDate = async (values) => {
    //console.log('Received values of form: ', values);
    setOpen(false);
    values.loginname = loginstate.role.loginname
    const r = await addtrigger(values);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(2);

    } else {
      messageerror(2);
    }

  };
  const save = async (key) => {
    //这里的row就是表单的所有项的值作为一个row对象存储
    //这里会异步
    const row = await form.validateFields();

    row.key = key;
    row.loginname = loginstate.role.loginname;

    //发送put请求到服务器
    const r = await edittrigger(row);
    //console.log(r);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(0);

    } else {
      messageerror(0);
    }
    setEditingKey('');
    setSelectedRowKeys([]); // 清除表格选择
    setparaisselected(false);//保存时让button不起作用
  };

  const cancel = () => { // 定义 cancel 函数以重置 editingKey state
    setEditingKey('');

  };
  const deldata = async (key) => { // 定义 cancel 函数以重置 editingKey state
    //console.log(key);
    const r = await deltrigger(key);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(1);

    } else {
      messageerror(1);
    }
    setEditingKey('');

  };
  const handleTableChange = (pagination, filters, sorter) => {

    setTableParams({
      pagination,
      //filters,
      // ...sorter,
    });

    // pagination分页异常值如果和tableParams里的分页异常值不一样，就把异常值清零，重新发送请求
    // if (pagination.pageSize !== tableParams.pagination?.pageSize) {
    //   setData([]);
    // }
  };
  //这个比EditableCell先执行，这个是点了edit后展示的form表单的设置
  const mergedColumns = columns.map((col) => { // 通过映射 columns 数组定义 mergedColumns 数组
    if (!col.editable) { // 如果列不可编辑，返回列
      return col;
    }

    return {
      ...col, // 否则返回编辑行新对象，其 render 函数为 EditableCell 组件
      onCell: (record) => (

        {

          record,
          //inputType: col.dataIndex === 'category' ? 'radio' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(record),//判断这一行的key是否为editingKey，为true说明这一行点击了edit
          // 将单元格的原始值传递给 EditableCell 组件

        }),
    };
  });

  //一旦tableParams发生改变，就调用此方法，当然第一次加载页面的时候也会调用此方法，所以第一次总是会去发送请求
  //useEffect 钩子函数将在组件渲染后执行 
  useEffect(() => {
    //如果请求成功则调用setTableParams方法

    if (result.isSuccess) {
      //console.log(result.data.pagedata);
      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: result.data.total,

        },
      });
    }

  }, [result.isSuccess]);//这样可以第一次分页也正常显示页码




  return (
    <>
      {/* 必须把contextHolder包裹整个组件才能显示message消息框 */}
      {contextHolder}
      <Button
        onClick={() => {
          setOpen(true);
        }}
        type="primary"
        //如果是admin登陆的就不需要执行添加特定用户参数
        disabled={loginstate.role.loginname === "admin"}
        style={{
          marginBottom: 16,
        }}
      // disabled={loginstate.role==="admin"?false:true}
      >
        添加
      </Button>
      <CollectionCreateForm
        open={open}
        onCreate={onAddDate}
        onCancel={() => {
          setOpen(false);
        }}
      />
      <Form form={form} component={false}>

        <Table
          components={{
            body: {
              cell: EditableCell, // 使用 EditableCell 组件作为表格单元格
            },
          }}
          bordered
          rowSelection={rowSelection}
          dataSource={result.isSuccess ? result.data.pagedata : []} // 将 dataSource prop 设置为异常值 state
          columns={mergedColumns} // 将 columns prop 设置为 mergedColumns 数组
          rowClassName="editable-row"
          pagination={tableParams.pagination}
          loading={result.isLoading}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
        />

        <Form.Item>
          {!loading ? (<Popover content={popovercontent} title="报文转csv按钮">
            <Button
              block type="primary"
              size="large"
              danger
              disabled={!paraisselected}
              onClick={datapredictexcute}
            >报文解析</Button>
          </Popover>)

            : (<Spin tip="报文转csv中……请不要切换页面！！！" size="large">
              <div className="content" />
            </Spin>)}
        </Form.Item>


      </Form>

      {excutesuccess === 1 ? <Alert
        message="已发送请求"
        description={<div dangerouslySetInnerHTML={{ __html: resultString }} />}
        type="success"
        showIcon

      /> : excutesuccess === 0 ? <Alert
        message="发送请求失败"
        description="报文转csv失败，请查看日志"
        type="Error"
        showIcon

      /> : <></>

      }

    </>
  )
}

export default DBCMessageTransferProp